//logs.js
const util = require('../../utils/util.js')
const db = wx.cloud.database()
const DB_User = db.collection('user')
const _ = db.command

const app = getApp()

Page({
  data: {
    logs: [],
    username: '',
    password: ''
  },
  register: function () {
    wx.navigateTo({
      url: '../register/register'
    })
  },
  gotoTest: function () {
    wx.navigateTo({
      url: '../index/index'
    })
  },
  onLoad: function () {
    this.setData({
      logs: (wx.getStorageSync('logs') || []).map(log => {
        return util.formatTime(new Date(log))
      })
    })
  },
  usernameChange: function (e) {
    this.setData({
      username: e.detail.value
    })
  },
  passwordChange: function (e) {
    this.setData({
      password: e.detail.value
    })
  },
  getInfo() {
    console.log(app.globalData.userInfo)
  },
  login: function () {
    console.log("login", this.data)
    if (this.data.username.length == 0 || this.data.password.length == 0) {
      wx.showToast({
        title: '用户名或密码不能为空',
        icon: 'none'
      })
      return
    }

    DB_User.where(_.or([{
      name: _.eq(this.data.username),
      password: _.eq(this.data.password)
    }, {
      number: _.eq(this.data.username),
      password: _.eq(this.data.password)
    }])).get({
      success: function (res) {
        console.log(res)
        if (res.data.length > 0) {
          if (res.data[0].status == '审核中') {
            wx.navigateTo({
              url: '../auditing/auditing',
            })
          } else {
            console.log(res.data[0])
            //1.存用户信息到本地存储
            res.data[0].password = ''
            wx.setStorageSync('userInfo', res.data[0])
            //2.存用户信息到全局变量
            app.globalData.userInfo = res.data[0]

            wx.switchTab({
              url: '../main/main',
            })
          }

        } else {
          wx.showToast({
            title: '用户名或密码错误',
            icon: 'none'
          })
        }

      },
      fail: function (res) {
        console.error(res)
      }
    })

  }

})